package com.mdd.common.pay.alipay;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;

@Component
public class AlipayHandle {

	/**
	 * 	支付宝APP支付
	 * @param orderSn		订单号
	 * @param amount		金额
	 * @param remark		备注
	 * @param notifyur		回调地址
	 * @return
	 */
	public Map<String,Object> createAliPayOrder(String orderSn,String amount,String remark,String notifyur){
		Map<String,Object> map = new HashMap<String, Object>();
		CertAlipayRequest certAlipayRequest = new CertAlipayRequest ();
		certAlipayRequest.setServerUrl(AliPayConfigUtils.SERVERURL);
		certAlipayRequest.setAppId(AliPayConfigUtils.APPID);
		certAlipayRequest.setPrivateKey(AliPayConfigUtils.APPPRIVATEKEY);
		certAlipayRequest.setFormat("json");	
		certAlipayRequest.setCharset("UTF-8");
		certAlipayRequest.setSignType("RSA2");
		certAlipayRequest.setCertPath(AliPayConfigUtils.PUBLICCERTPATH);
		certAlipayRequest.setAlipayPublicCertPath(AliPayConfigUtils.PUBLICCERTRAS2PATH);
		certAlipayRequest.setRootCertPath(AliPayConfigUtils.ROOTCERTPATH);
		AlipayClient alipayClient = null;
		try {
			alipayClient = new DefaultAlipayClient(certAlipayRequest);
		} catch (AlipayApiException e1) {
			e1.printStackTrace();
		}
		//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
		AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
		model.setSubject(remark);
		model.setBody(remark);
		model.setOutTradeNo(orderSn);
		model.setTotalAmount(amount);
		model.setTimeoutExpress("1c");
		model.setProductCode("QUICK_MSECURITY_PAY");
		//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
		AlipayTradeAppPayRequest appPayRequest = new AlipayTradeAppPayRequest();
		appPayRequest.setBizModel(model);
		appPayRequest.setNotifyUrl(notifyur);// 回调地址
		try {
			AlipayTradeAppPayResponse appPayResponse = alipayClient.sdkExecute(appPayRequest);
			String body = appPayResponse.getBody();
			System.out.println("支付宝返回值：");
			System.out.println(body);
			map.put("body", body);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return map;
	}

	/**
	 * 	支付宝原路返回
	 * @param tradeNo			支付宝订单号
	 * @param amount			退款金额
	 * @param refundReason		退款理由
	 * @return
	 * 
	 * if(!"SUCCESS".equals(retStr)) {
				cap.setRemark(cap.getRemark()+"-退款失败！");
				cap.setNameType(retStr);
				userCapitalFlowService.save(cap);
				return;
			}
	 */
	public String aliPayOriginalRefund(String tradeNo,BigDecimal amount,String refundReason) {
		String retStr = "SUCCESS";
		try {
			//构造client
			CertAlipayRequest certAlipayRequest = new CertAlipayRequest ();

			//设置网关地址
			certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
			//设置应用Id
			certAlipayRequest.setAppId(AliPayConfigUtils.APPID);
			//设置应用私钥
			certAlipayRequest.setPrivateKey(AliPayConfigUtils.APPPRIVATEKEY);
			//设置请求格式，固定值json
			certAlipayRequest.setFormat("json");	
			//设置字符集
			certAlipayRequest.setCharset("UTF-8");
			//设置签名类型
			certAlipayRequest.setSignType("RSA2");
			//设置应用公钥证书路径
			certAlipayRequest.setCertPath(AliPayConfigUtils.PUBLICCERTPATH);
			//设置支付宝公钥证书路径
			certAlipayRequest.setAlipayPublicCertPath(AliPayConfigUtils.PUBLICCERTRAS2PATH);
			//设置支付宝根证书路径
			certAlipayRequest.setRootCertPath(AliPayConfigUtils.ROOTCERTPATH);
			//构造client
			AlipayClient alipayClient = null;
			try {
				alipayClient = new DefaultAlipayClient(certAlipayRequest);
			} catch (AlipayApiException e1) {
				e1.printStackTrace();
			}
			AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
			JSONObject bizContent = new JSONObject();
			bizContent.put("trade_no", tradeNo);
			bizContent.put("refund_amount", amount);
			bizContent.put("refund_reason", "快点嘛-"+refundReason);
			request.setBizContent(bizContent.toString());
			AlipayTradeRefundResponse response = alipayClient.certificateExecute(request);
			System.out.println(response.getBody());
			if(!response.isSuccess()){
				JSONObject parseObject = JSONObject.parseObject(response.getBody());
				retStr = parseObject.getString("code")+","+parseObject.getString("msg")+","+parseObject.getString("sub_code");
			}
		} catch (Exception e) {
			retStr = e.getMessage();
		}
		return retStr;
	}

	
	// 网站支付
	public String getQrCode(String orderNo,String amount,String remark,String notifyUrl) {
		AlipayClient client =  new  DefaultAlipayClient( "https://openapi.alipay.com/gateway.do" , AliPayConfigUtils.APPID, 
				AliPayConfigUtils.APPPRIVATEKEY, "json", "UTF-8", AliPayConfigUtils.APPPUBLICKEY, "RSA2");  //获得初始化的AlipayClient 
		String payPath = "";
		try {
			JSONObject bizContent = new JSONObject();
			bizContent.put("out_trade_no", orderNo);
			bizContent.put("total_amount", amount);
			bizContent.put("subject", remark);
			bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
			AlipayTradePagePayRequest  request = new AlipayTradePagePayRequest ();
			request.setBizContent(bizContent.toString());
			request.setNotifyUrl(notifyUrl);
			request.setReturnUrl("https://pc.kdkdkd.cn/member");
			AlipayTradePagePayResponse response = client.pageExecute(request);
			String body = response.getBody();
			payPath = body;
		} catch (Exception e) {
			e.printStackTrace();
			payPath = "";
		}
		return payPath;
	}

}
